<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑案件' : '新增案件'"
    width="600px"
    :before-close="handleClose"
  >
    <div class="case-form">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="案件编号" prop="caseNumber">
          <el-input
            v-model="formData.caseNumber"
            placeholder="请输入案件编号"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="当事人" prop="parties">
          <el-input
            v-model="formData.parties"
            type="textarea"
            placeholder="请输入当事人信息"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
          <div class="form-tip">请详细描述当事人信息，包括原告、被告等</div>
        </el-form-item>
        
        <el-form-item label="审理法院" prop="court">
          <el-input
            v-model="formData.court"
            placeholder="请输入审理法院"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="案件状态" prop="status">
          <el-select
            v-model="formData.status"
            placeholder="请选择案件状态"
            style="width: 100%"
          >
            <el-option
              v-for="option in CASE_STATUS_OPTIONS"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            >
              <div class="status-option">
                <el-tag :type="option.type" size="small">
                  {{ option.label }}
                </el-tag>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="关联文档" prop="documentId">
          <el-select
            v-model="formData.documentId"
            placeholder="请选择关联的法律文档"
            filterable
            clearable
            style="width: 100%"
            @focus="fetchDocuments"
          >
            <el-option
              v-for="doc in documentOptions"
              :key="doc.id"
              :label="doc.title"
              :value="doc.id"
            >
              <div class="document-option">
                <span class="doc-title">{{ doc.title }}</span>
                <el-tag :type="getDocTypeTagType(doc.docType)" size="small">
                  {{ DOC_TYPES[doc.docType] }}
                </el-tag>
              </div>
            </el-option>
          </el-select>
          <div class="form-tip">选择与此案件相关的法律文档</div>
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          :loading="submitLoading"
          @click="handleSubmit"
        >
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { createCase, updateCase, CASE_STATUS_OPTIONS } from '../../../api/case'
import { getDocumentPage, DOC_TYPES } from '../../../api/document'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  caseData: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:visible', 'refresh'])

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 表单引用
const formRef = ref()

// 是否编辑模式
const isEdit = computed(() => !!props.caseData?.id)

// 提交加载状态
const submitLoading = ref(false)

// 文档选项
const documentOptions = ref([])

// 表单数据
const formData = reactive({
  id: null,
  caseNumber: '',
  parties: '',
  court: '',
  status: null,
  documentId: null
})

// 表单验证规则
const formRules = {
  caseNumber: [
    { required: true, message: '请输入案件编号', trigger: 'blur' },
    { max: 50, message: '案件编号不能超过50个字符', trigger: 'blur' }
  ],
  parties: [
    { required: true, message: '请输入当事人信息', trigger: 'blur' },
    { max: 500, message: '当事人信息不能超过500个字符', trigger: 'blur' }
  ],
  court: [
    { required: true, message: '请输入审理法院', trigger: 'blur' },
    { max: 100, message: '审理法院不能超过100个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择案件状态', trigger: 'change' }
  ]
}

// 获取文档类型标签样式
const getDocTypeTagType = (docType) => {
  const typeMap = {
    0: 'danger',   // 法律 - 红色
    1: 'primary',  // 案例 - 蓝色
    2: 'warning',  // 判决书 - 橙色
    3: 'success'   // 文章 - 绿色
  }
  return typeMap[docType] || 'info'
}

// 获取文档列表
const fetchDocuments = async () => {
  if (documentOptions.value.length > 0) return
  
  try {
    const response = await getDocumentPage({ pageNum: 1, pageSize: 1000 })
    if (response.code === 200) {
      documentOptions.value = response.data.records
    }
  } catch (error) {
    console.error('获取文档列表失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    caseNumber: '',
    parties: '',
    court: '',
    status: null,
    documentId: null
  })
  formRef.value?.resetFields()
}

// 关闭对话框
const handleClose = () => {
  resetForm()
  // 通知父组件清空数据
  emit('update:caseData', null)
  emit('update:visible', false)
}

// 提交表单
const handleSubmit = async () => {
  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    submitLoading.value = true
    
    const submitData = { ...formData }
    
    let response
    if (isEdit.value) {
      response = await updateCase(submitData)
    } else {
      delete submitData.id
      response = await createCase(submitData)
    }

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      emit('refresh')
      handleClose()
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 监听案件数据变化，回填表单
watch(() => props.caseData, (newData) => {
  if (newData) {
    Object.assign(formData, {
      id: newData.id,
      caseNumber: newData.caseNumber || '',
      parties: newData.parties || '',
      court: newData.court || '',
      status: newData.status,
      documentId: newData.documentId || null
    })
  }
}, { immediate: true })

// 监听对话框打开，获取文档列表
watch(dialogVisible, (visible) => {
  if (visible) {
    // 每次打开都先重置表单，避免数据残留
    resetForm()
    fetchDocuments()
    // 如果是编辑模式，在下一个tick重新设置数据
    if (props.caseData) {
      nextTick(() => {
        Object.assign(formData, {
          id: props.caseData.id,
          caseNumber: props.caseData.caseNumber || '',
          parties: props.caseData.parties || '',
          court: props.caseData.court || '',
          status: props.caseData.status,
          documentId: props.caseData.documentId || null
        })
      })
    }
  }
})
</script>

<style scoped>
.case-form {
  padding: 0 20px;
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
  line-height: 1.4;
}

.status-option {
  display: flex;
  align-items: center;
}

.document-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.doc-title {
  flex: 1;
  margin-right: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .case-form {
    padding: 0 10px;
  }
  
  :deep(.el-form-item__label) {
    line-height: 1.2;
  }
}
</style>
